package com.bms.tools;

import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.bms.comm.MyAuthenticator;

@Component
public class MailSender {
	
	@Resource
	private JavaMailSenderImpl javaMailSender;
	
	@Resource
	private SimpleMailMessage simpleMailMessage;
	
	@Resource
	private ThreadPoolTaskExecutor taskExecutor;
	
	public void sendEMail(String to, String subject, String content){
		
		try{
			MimeMessage message = javaMailSender.createMimeMessage();            
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");            
			messageHelper.setFrom(simpleMailMessage.getFrom());            
			if (subject != null) {                
				messageHelper.setSubject(subject);            
			} else {                
				messageHelper.setSubject(simpleMailMessage.getSubject());            
			}            
			messageHelper.setTo(to);            
			messageHelper.setText(content, true);  
			
			// 添加验证  
	        MyAuthenticator auth = new MyAuthenticator(javaMailSender.getUsername(),  
	        		javaMailSender.getPassword());  
	        Properties props = javaMailSender.getJavaMailProperties();
	        Session session = Session.getDefaultInstance(props, auth);  
	        javaMailSender.setSession(session); 
	        
			javaMailSender.send(message);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
